from django.conf import settings
from django.apps import apps
from django.db import connection


class TenantMigrationRouter:
    """
    根据当卡锁定的Schema，是否应该对一个model执行数据迁移。
    
    下述任一条件满足，则允许迁移该model：

    1) 如果当前的锁定Schema是装满满的租户Schema，且当前的model需要一个独占Schema
    2) 如果当前的锁定Schema是public，且当前的model可以共享
    """

    def _is_zmm_schema(self, schema_name: str):
        return schema_name.lower().startswith('zmm_')

    def _is_scoped_app(self, app_name: str):
        app_obj = apps.get_app_config(app_name)
        return getattr(app_obj, 'scoped', False)

    def allow_migrate(self, db, app_label, model_name=None, **options):
        # 如果使用的DatabaseWrapper是原生的，则无法使用该Router的功能
        db_engine = settings.DATABASES[db]['ENGINE']

        if db_engine != 'common.psql_backend':
            return None

        # 确定当前锁定的Schema是什么
        target_schema = connection.primary_schema

        # 判断条件 1)
        if self._is_zmm_schema(target_schema) and self._is_scoped_app(app_label):
            return None

        # 判断条件 2)
        if target_schema == 'public' and not self._is_scoped_app(app_label):
            # All shared apps are migrated to the "public" schema
            return None
        
        # 拒绝迁移该model
        return False
